package nero.yncc.com.createart.custom;

import android.animation.AnimatorSet;
import android.animation.TypeEvaluator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.BounceInterpolator;
import android.widget.LinearLayout;

import android.animation.AnimatorSet;
import android.animation.TypeEvaluator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.BounceInterpolator;
import android.widget.LinearLayout;

/**
 * Created by nero on 2017/6/14.
 */

public class CustomUpView extends LinearLayout {

    ViewTop viewTop;   //顶部View
    ViewBottom viewBottom;   //底部view

    int screenHeight = 0; //屏幕高度
    int screenWidth = 0; //屏幕高度

    int nowHeight = 0;  //当前高度

    float nowScale = 0.0f; //当前拉的比例
    int bottomWidth = 0;   //底部宽度
    double bottomTranslate = 1.0f; //底部透明度
    double topTranslate = 1.0f; //顶部透明度

    float needHeightScale = 0.5f;//当下面滑动到屏幕高度的多少进行判断是还原还是上拉操作

    MyGestureListener gestureListener;  //手势监听
    GestureDetector gestureDetector;    //手势托管

    public CustomUpView(Context context) {
        super(context);
        init();
    }

    public CustomUpView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }


    /**
     * 初始化 获取屏幕高度 设置宽高占满屏幕 添加顶部和底部View 两个VIew垂直存在
     */
    private void init() {
        WindowManager manager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics matrix = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(matrix);
        screenHeight = matrix.heightPixels;
        screenWidth = matrix.widthPixels;
        //设置布局
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(-1, -1);
        setLayoutParams(layoutParams);
        setGravity(Gravity.CENTER);

        //添加两个部件
        viewTop = new ViewTop(getContext());
        viewBottom = new ViewBottom(getContext());

        setOrientation(LinearLayout.VERTICAL);
        addView(viewTop);
        addView(viewBottom);

        //手势监听类
        gestureListener = new MyGestureListener();
        gestureDetector = new GestureDetector(gestureListener);

        setLongClickable(true);


        setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    //在这里判断是否有拉来超越限制 进行还原或者新建操作
                    ValueAnimator animator_height = null;
                    ValueAnimator animator_width = null;
                    ValueAnimator animator_alpha_top = null;
                    ValueAnimator animator_alpha_bottom = null;
                    if (nowHeight >= screenHeight * needHeightScale) {
                        //还原
                        animator_height = ValueAnimator.ofObject(new HeightEvalutor(), nowHeight, screenHeight);
                        animator_width = ValueAnimator.ofObject(new WeightEvalutor(), bottomWidth, 0);
                        animator_alpha_top = ValueAnimator.ofFloat((float) topTranslate, 1.0f);
                        animator_alpha_bottom = ValueAnimator.ofFloat((float) bottomTranslate, 0.0f);
                    } else {
                        //上拉
                        animator_height = ValueAnimator.ofObject(new HeightEvalutor(), nowHeight, 0);
                        animator_width = ValueAnimator.ofObject(new WeightEvalutor(), bottomWidth, screenWidth);
                        animator_alpha_top = ValueAnimator.ofFloat((float) topTranslate, 0.0f);
                        animator_alpha_bottom = ValueAnimator.ofFloat((float) bottomTranslate, 1.0f);
                    }
                    animator_alpha_top.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                            viewTop.setAlpha((float) animation.getAnimatedValue());
                        }
                    });

                    animator_alpha_bottom.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                            viewBottom.setAlpha((float) animation.getAnimatedValue());
                        }
                    });

                    animator_height.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                            viewTop.setHeight((int) animation.getAnimatedValue());
                        }
                    });
                    animator_width.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                            viewBottom.setWidth((int) animation.getAnimatedValue());
                        }
                    });
                    //设置动画的弹跳差值器
                    animator_height.setInterpolator(new BounceInterpolator());
                    animator_height.setDuration(500);

                    animator_width.setInterpolator(new BounceInterpolator());
                    animator_width.setDuration(500);

                    AnimatorSet set = new AnimatorSet();
                    set.play(animator_height).with(animator_width);
                    set.start();
                    return true;
                } else {
                    return gestureDetector.onTouchEvent(event);
                }
            }
        });

    }

    /**
     * 再顶部添加布局
     * */
    public void addViewTop(View view) {
        viewTop.addViewFull(view);
    }
    /**
     * 再底部添加布局
     * */
    public void addViewBottom(View view) {
        viewBottom.addViewFull(view);
    }
    /**
     * 高度估值器
     */
    private class HeightEvalutor implements TypeEvaluator<Integer> {

        @Override
        public Integer evaluate(float fraction, Integer startValue, Integer endValue) {

            return Float.valueOf((nowHeight + fraction * (endValue - startValue))).intValue();
        }
    }

    /**
     * 宽度估值器
     */
    private class WeightEvalutor implements TypeEvaluator<Integer> {

        @Override
        public Integer evaluate(float fraction, Integer startValue, Integer endValue) {

            return Float.valueOf((bottomWidth + fraction * (endValue - startValue))).intValue();
        }
    }

    /**
     * 手势类监听器
     */
    private class MyGestureListener implements GestureDetector.OnGestureListener {

        @Override
        public boolean onDown(MotionEvent e) {
            Log.e("1123", "onDown");
            return false;
        }

        @Override
        public void onShowPress(MotionEvent e) {
            Log.e("1123", "onShowPress");
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {

            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            //滑动的时候高度等于屏幕高度加上滑动距离(正负不管) 然后判断是否溢出屏幕进行阻止
            nowHeight = (int) (screenHeight + e2.getY() - e1.getY());
            if (nowHeight < 0) {
                nowHeight = 0;
            } else if (nowHeight > screenHeight) {
                nowHeight = (int) screenHeight;
            }


            viewTop.setHeight(nowHeight);
            //滑动的同时吧底部view宽度和透明度进行缩放  比例：top高度和屏幕高度比例
            nowScale = (float) nowHeight / (float) screenHeight;

            bottomWidth = screenWidth - (int) (screenWidth * nowScale);
            bottomTranslate = 1 - nowScale * 1.5;
            if (bottomTranslate <= 0.8) {
                //在这里给它多添加0.2的透明度 不然太慢
                bottomTranslate += 0.2;
            }

            viewBottom.setWidth(bottomWidth);
            viewBottom.setAlpha((float) bottomTranslate);

            topTranslate = nowScale * 1.5;
            viewTop.setAlpha((float) topTranslate);
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            Log.e("1123", "onLongPress");
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            return false;
        }
    }


    /**
     * 顶部的容器类
     */
    class ViewTop extends LinearLayout {
        LinearLayout.LayoutParams layoutParams;

        public ViewTop(Context context) {
            super(context);
            init();
        }

        private void init() {
            layoutParams = new LinearLayout.LayoutParams(-1, -1);
            setLayoutParams(layoutParams);

            setBackgroundColor(Color.RED);
        }

        public void setHeight(int height) {
            layoutParams = new LinearLayout.LayoutParams(-1, height);
            setLayoutParams(layoutParams);

        }

        public void addViewFull(View view) {
            LinearLayout.LayoutParams params_view = new LinearLayout.LayoutParams(-1, -1);
            view.setLayoutParams(params_view);
            addView(view);
        }
    }

    /**
     * 底部的容器类
     */
    class ViewBottom extends LinearLayout {
        LinearLayout.LayoutParams layoutParams;

        public ViewBottom(Context context) {
            super(context);
            init();
        }

        private void init() {
            layoutParams = new LinearLayout.LayoutParams(0, -1);
            setLayoutParams(layoutParams);

            setBackgroundColor(Color.WHITE);
        }

        public void setWidth(int width) {
            layoutParams.width = width;
        }

        public void addViewFull(View view) {
            LinearLayout.LayoutParams params_view = new LinearLayout.LayoutParams(-1, -1);
            view.setLayoutParams(params_view);
            addView(view);
        }
    }
}
